<script setup lang="ts">
import { NButton, NIcon, NPopconfirm } from 'naive-ui'
import { SearchOutline, AddOutline } from '@vicons/ionicons5'
import { Reset } from '@vicons/carbon'
import { useUserStore } from '@/stores'
import { onMounted, type Ref, ref, reactive } from 'vue'
import { topicGetTopicListService, topicDeleteTopicService } from '@/api/topic'
import { DeleteOutlined } from '@vicons/antd'
import { formatTime } from '@/utils/format'
import TopicDrawer from '@/views/Topic/components/TopicDrawer.vue'

const userStore = useUserStore()
const message = useMessage()
//帖子数量
const count: Ref<number> = ref(0)
//是否在加载
const isLoading: Ref<boolean> = ref(false)
//获取帖子列表
const data: Ref<Api.Topic.TopicInfo[]> = ref([])
const kindNumber: Ref<number> = ref(0)
//帖子的类别
onMounted(async () => {
  isLoading.value = true
  const res = await topicGetTopicListService({ t_uid: userStore.userInfo.id })
  count.value = res.data.data.length
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  //统计文章标签数量
  const kind = new Set()
  data.value.forEach((item) => {
    kind.add(item.t_kind)
  })
  kindNumber.value = kind.size
  isLoading.value = false
  console.log(res)
})

type RowData = {
  id: number
  t_title: string
  t_kind: string
  create_time: string
  t_photo: string
  t_introduce: string
}
const createColumns = () => {
  return [
    {
      type: 'selection',
      fixed: 'left'
    },
    {
      title: 'ID',
      key: 'id',
      fixed: 'left',
      width: 100
    },
    {
      title: '帖子名称',
      key: 't_title',
      fixed: 'left',
      width: 100
    },
    {
      title: '帖子类别',
      key: 't_kind',
      width: 100
    },
    {
      title: '创建时间',
      key: 'create_time',
      width: 100
    },
    {
      title: '封面',
      key: 't_photo',
      width: 50,
      render(row: RowData) {
        return h('img', {
          src: row.t_photo,
          style: {
            width: '40px',
            height: '40px'
          }
        })
      }
    },
    {
      title: '简介',
      key: 't_introduce',
      width: 200
    },
    {
      title: '操作',
      key: 'actions',
      fixed: 'right',
      width: 150,
      render: (row: RowData) => {
        return h(
          'div',
          {
            style: {
              display: 'flex',
              justifyContent: 'start',
              gap: '8px'
            }
          },
          {
            default: () => [
              h(
                NButton,
                { type: 'info', ghost: true, size: 'small', onClick: () => openDrawer(row.id) },
                { default: () => '编辑' }
              ),
              h(
                NPopconfirm,
                { positiveText: '确定', negativeText: '取消', onPositiveClick: () => handleDelete(row.id) },
                {
                  trigger: () => h(NButton, { type: 'error', ghost: true, size: 'small' }, { default: () => '删除' }),
                  default: () => '你确定要删除吗？'
                }
              )
            ]
          }
        )
      }
    }
  ]
}
const columns = createColumns()
// 分页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30],
  onChange: (page: number) => {
    paginationReactive.page = page
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
  }
})
//搜索
type SearchForm = {
  t_uid: number | null
  t_title: string | null
  t_kind: string | null
}
const defaultSearchForm: SearchForm = {
  t_uid: userStore.userInfo.id,
  t_title: null,
  t_kind: null
}
const searchForm: Ref<SearchForm> = ref({
  ...defaultSearchForm
})
const onSearch = async () => {
  const res = await topicGetTopicListService({
    t_uid: userStore.userInfo.id,
    t_title: searchForm.value.t_title,
    t_kind: searchForm.value.t_kind
  })
  data.value = res.data.data
  paginationReactive.page = 1
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('搜索成功')
}
//重置
const onReset = async () => {
  searchForm.value = { ...defaultSearchForm }
  paginationReactive.page = 1
  //恢复全部的数据
  const res = await topicGetTopicListService({ t_uid: userStore.userInfo.id })
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('重置成功')
}
//处理删除
const handleDelete = async (id: number) => {
  await topicDeleteTopicService([id])
  //获取数据
  const res = await topicGetTopicListService({ t_uid: userStore.userInfo.id })
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('删除成功')
  paginationReactive.page = 1
}
//处理批量删除
const checkedKeys: Ref<number[]> = ref<number[]>([])
//更新选中的行，返回选中的行的key，选择的行更新时触发
const onUpdateCheckedRowKeys = (keys: number[]) => {
  checkedKeys.value = keys
  console.log(keys)
}
const handleBatchGenerationDelete = async () => {
  await topicDeleteTopicService(checkedKeys.value)
  //获取数据
  const res = await topicGetTopicListService({ t_uid: userStore.userInfo.id })
  data.value = res.data.data
  //对数据的时间戳进行格式化
  data.value.forEach((item) => {
    item.create_time = formatTime(item.create_time)
  })
  message.success('删除成功')
  paginationReactive.page = 1
}
//处理数据更新
const handleUpdate = async (operate: string) => {
  if (operate === 'edit') {
    const res = await topicGetTopicListService({ t_uid: userStore.userInfo.id })
    data.value = res.data.data
    //对数据的时间戳进行格式化
    data.value.forEach((item) => {
      item.create_time = formatTime(item.create_time)
    })
  }
  if (operate === 'add') {
    //回到第一页
    paginationReactive.page = 1
    //重新获取数据
    const res = await topicGetTopicListService({ t_uid: userStore.userInfo.id })
    data.value = res.data.data
    //对数据的时间戳进行格式化
    data.value.forEach((item) => {
      item.create_time = formatTime(item.create_time)
    })
  }
}
//打开抽屉
const drawRef = ref()
const openDrawer = (id?: number) => {
  if (id) {
    drawRef.value.open(id)
  } else {
    drawRef.value.open()
  }
}
</script>
<template>
  <div class="flex justify-center flex-col gap-4">
    <NCard class="h-15 flex justify-center">
      <n-form class="flex flex-items-center" :model="searchForm">
        <NGrid :cols="24" x-gap="24">
          <n-form-item-gi :span="6">
            <n-input placeholder="帖子名称" v-model:value="searchForm.t_title" />
          </n-form-item-gi>
          <n-form-item-gi :span="6">
            <n-input placeholder="帖子类别" v-model:value="searchForm.t_kind" />
          </n-form-item-gi>
          <n-form-item-gi :span="2" :offset="8">
            <n-button type="info" strong secondary size="medium" icon-placement="left" @click="onSearch">
              <template #icon>
                <n-icon>
                  <SearchOutline />
                </n-icon>
              </template>
              搜索
            </n-button>
          </n-form-item-gi>
          <n-form-item-gi :span="2">
            <n-button type="default" strong secondary size="medium" icon-placement="left" @click="onReset">
              <template #icon>
                <n-icon>
                  <Reset />
                </n-icon>
              </template>
              重置
            </n-button>
          </n-form-item-gi>
        </NGrid>
      </n-form>
    </NCard>
    <NCard>
      <div class="flex justify-between">
        <n-h4>共有帖子：{{ count }} 条</n-h4>
        <n-space class="flex gap-4">
          <NButton type="info" size="small" icon-placement="left" ghost :on-click="() => openDrawer()">
            <template #icon>
              <NIcon>
                <AddOutline />
              </NIcon>
            </template>
            新增
          </NButton>
          <n-popconfirm @positive-click="handleBatchGenerationDelete" positive-text="确定" negative-text="取消">
            <template #trigger>
              <n-button type="error" size="small" ghost>
                <template #icon>
                  <n-icon>
                    <DeleteOutlined />
                  </n-icon>
                </template>
                批量删除
              </n-button>
            </template>
            你确定要删除吗？
          </n-popconfirm>
        </n-space>
      </div>
      <NDataTable
        :columns="columns"
        :data="data"
        :row-key="(row: RowData) => row.id"
        :max-height="320"
        :min-height="320"
        :scroll-x="1200"
        virtual-scroll
        :pagination="paginationReactive"
        size="small"
        :loading="isLoading"
        flex-height
        @update:checked-row-keys="onUpdateCheckedRowKeys"
      ></NDataTable>
    </NCard>
  </div>
  <TopicDrawer ref="drawRef" @updateData="handleUpdate"></TopicDrawer>
</template>
